/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package downloadmanager;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import util.ClipboardExtensions;
import util.FileExtensions;

/**
 *
 * @author Administrator
 */
public class NewDownloadDialog extends JDialog {

    String url;
    String savePath;
    boolean added = false;//indicate whether user has press add button yet
    final JTextField txtUrl;
    final JFileChooser fileChooser;

    public NewDownloadDialog() {
        setTitle("Add new download");
        setModalityType(ModalityType.APPLICATION_MODAL);

        setLayout(new FlowLayout(FlowLayout.CENTER));
        setPreferredSize(new Dimension(450, 400));

        JLabel label = new JLabel("Url");
        txtUrl = new JTextField();

        fileChooser = new JFileChooser();
        fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
        fileChooser.setApproveButtonText("Add");
        fileChooser.setApproveButtonMnemonic(KeyEvent.VK_A);
        fileChooser.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = (JFileChooser) e.getSource();
                String command = e.getActionCommand();
                if (command.equals(JFileChooser.APPROVE_SELECTION)) {
                    File selectedFile = fileChooser.getSelectedFile();
                    url = txtUrl.getText();
                    if (!url.toLowerCase().startsWith("http://")) {
                        JOptionPane.showMessageDialog(txtUrl.getParent().getParent(), "Invalid prototcol. Only http is supported.", "Error", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    if (!selectedFile.exists() || JOptionPane.showConfirmDialog(fileChooser.getParent(), "Do you want to overwrite existed file?", "File existed", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {
                        savePath = selectedFile.getAbsolutePath();
                        added = true;
                        setVisible(false);
                    }
                } else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
                    setVisible(false);
                }
            }
        });

        //try to keep the save file name and url's path in sync
        txtUrl.getDocument().addDocumentListener(new DocumentListener() {

            public void changedUpdate(DocumentEvent e) {
                update();
            }

            public void removeUpdate(DocumentEvent e) {
                update();
            }

            public void insertUpdate(DocumentEvent e) {
                update();
            }
        });

        URL urlFromClipboard = getNormalizedUrl(ClipboardExtensions.getText());
        if (urlFromClipboard != null) {
            txtUrl.setText(urlFromClipboard.toString());
        }

        JPanel p1 = new JPanel(new BorderLayout());
        p1.setPreferredSize(new Dimension(400, 20));
        p1.add(label, BorderLayout.WEST);
        p1.add(txtUrl, BorderLayout.CENTER);

        JPanel p2 = new JPanel(new BorderLayout());
        p2.setPreferredSize(new Dimension(400, 300));
        p2.add(fileChooser);
        add(p1);
        add(p2);
        pack();

    }

    private void update() {
        URL normalizedUrl = getNormalizedUrl(txtUrl.getText());
        if (normalizedUrl != null) {
            try {
                File selectedFile = new File(fileChooser.getCurrentDirectory(), normalizedUrl.getPath());
                String similarFilename = FileExtensions.getSimilarNonExistentFile(selectedFile.getCanonicalPath());
                fileChooser.setSelectedFile(new File(similarFilename));
            } catch (IOException ex) {
                Logger.getLogger(NewDownloadDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    private URL getNormalizedUrl(String url) {
        // Only allow HTTP URLs.
        if (url == null) {
            return null;
        }
        if (!url.toLowerCase().startsWith("http://")) {
            return null;
        }

        // Verify format of URL.
        URL normalizedUrl = null;
        try {
            normalizedUrl = new URL(url);
        } catch (Exception e) {
            return null;
        }

        // Make sure URL specifies a file.
        if (normalizedUrl.getFile().length() < 2) {
            return null;
        }

        return normalizedUrl;
    }

    public static void main(String[] args) {
        System.out.println(getDownloadJob());
    }

    public static DownloadJob getDownloadJob() {
        NewDownloadDialog frame = new NewDownloadDialog();
        frame.show();
        DownloadJob job = null;
        if (frame.added) {
            job = new DownloadJob(frame.url, frame.savePath);
        }
        frame.dispose();
        return job;
    }
}
